/*
var m = require('memcached'),memcached;
	memcached = new m("127.0.0.1:11211");
*/
var clients = new Array();
var users = new Array();
var WebSocket = require('ws');
var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({port: 8080});
var count = 0;

//data = {user_id:'',to:'',content:'',is_init:''};
wss.on('connection', function(ws) {
	count++;
	ws.on('message', function(message) {
		message = JSON.parse(message);
		if (message.is_init) {
			var user_id = message.user_id;
			clients[user_id] = ws;
			ws.send(JSON.stringify(message));
		}else {
			if (message.to) {
				var to = message.to;
				try{
					clients[to].send(JSON.stringify(message));
				}catch(e){
					console.dir(e);
				}
				
			}else {
				wss.broadcast(JSON.stringify(message));
			}
		}
	});
	ws.on('close',function(){
		count--;
		console.log('close');
	});
	wss.broadcast('{"user_id":"admin","content":"欢迎"}');
});

wss.broadcast = function(data) {
	for(var i in this.clients)
		this.clients[i].send(data);
};
/*
setInterval(function(){
		
}, 5000);
*/
/*
setInterval(function(){
		memcached.get("n_msg", function( err, result ){
	  		if( err ) console.error( err );
	  		//console.dir( result );
		});
	}, 5000);
*/
	